/******************************************************************
MIT License http://www.opensource.org/licenses/mit-license.php
Author Mora <qiuzhongleiabc@126.com> (https://github.com/qiu8310)
*******************************************************************/

import { Url, wxp } from '@minapp/core'
import { MobxApp } from '@minapp/mobx'
import { MyStore } from './MyStore'

interface requestOption {
  api: string | any;
  id?: number;
  params?: object;
  method?: string;
  login?: boolean;
  silence?: boolean;
}

export class MyApp extends MobxApp<MyStore> {
  // @ts-ignore
  $url: {
    /*
      注意：
        1. INJECT_START 到 INJECT_END 之间的文件是自动注入的，请不要随意修改
        2. 注入规则写在 .dtpl 文件夹中的 dtpl.js 文件中
        3. 需要安装 vscode 插件 dot-template-vscode 来达到注入功能
        4. 触发条件是：每次在 src/pages 目录下新建一个空文件夹时
    */

    /*# INJECT_START {"key": "pagesMap"} #*/
    index: Url
    logs: Url
    home: Url
    good_details: Url
    mine: Url
    cart: Url
    category: Url
    orders: Url
    /*# INJECT_END #*/
  }

  async userLogin() {
    const { code } = await wxp.login()
    const { data: { session_id } } = await this.basePost({ api: 'xcx/getsession', params: { code } })
    this.store.sessionId = session_id

    // 获取用户信息
    const { encryptedData, iv } = await Promise.resolve(session_id).then(() => wxp.getUserInfo())
    const { data } = await this.create({ api: 'xcx/setlogin', params: { encryptedData, iv } })
    wxp.setStorageSync('userInfo', data)
  }

  baseRequest({ api, id, method, params = {}, login = false, silence = false }: requestOption) {
    if (!silence) {
      wxp.showLoading({ title: '加载中...' })
    }
    return wxp.request({
      url: `https://mall.hellogreens.cn/api/${api}/${id || ''}`,
      header: {
        'session-id': this.store.sessionId
      },
      method: method || 'GET',
      data: params
    })
      .then(res => (res.statusCode >= 400 ? Promise.reject(res.statusCode) : res.data))
      .catch(err => {
        console.error(err)
        wxp.showToast({ title: '网络错误，请稍后再试' })
      })
      .finally((): any => wxp.hideLoading())
  }

  checkSession() {
    return wxp.checkSession()
      .catch(() => this.userLogin())
  }

  basePost({ api, id, params = {} }: requestOption) {
    return this.baseRequest({ api, id, method: 'POST', params })
  }

  create({ api, id, params = {} }: requestOption) {
    return this.checkSession().then(() => this.basePost({ api, id, params }))
  }

  fetch({ api, id, params = {} }: requestOption) {
    return this.checkSession().then(() => this.baseRequest({ api, id, params }))
  }

  patch({ api, id, params = {} }: requestOption) {
    params = Object.assign({}, params, { _method: 'PUT' })
    return this.checkSession().then(() => this.basePost({ api, id, params }))
  }

  remove({ api, id }: requestOption) {
    const params = { _method: 'DELETE' }
    return this.checkSession().then(() => this.basePost({ api, id, params }))
  }

  // 提取 event 数据
  getData(e: any, key: string) {
    const { currentTarget: { dataset } } = e
    return dataset[key]
  }
}
